package com.ocom.payconfig.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ocom.common.AcpService;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.dto.payconfig.FeeDataGzhVo;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.human.EntityPersonTagRelation;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.payconfig.EntityTimingtaskLog;
import com.ocom.common.entity.payconfig.FeeData;
import com.ocom.common.request.simple.GzhMsgRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.DeepCopyUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.FeeItemXMVo;
import com.ocom.payconfig.client.MqSimpleFeign;
import com.ocom.payconfig.client.PayhandleClientService;
import com.ocom.payconfig.client.UgcapiFeign;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
public class TimingController {

    @Autowired
    private CompanyListInfoService companyListInfoService;

    @Autowired
    private TimingtaskLogService timingtaskLogService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private FeeItemService feeItemService;

    @Autowired
    private FeeDataService feeDataService;

    @Autowired
    private PersonTagRelationService personTagRelationService;

    @Autowired
    private XfMealLeaveService xfMealLeaveService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Autowired
    private MqSimpleFeign mqSimpleFeign;

    @Autowired
    private UgcapiFeign ugcapiFeign;

    @Autowired
    private PayhandleClientService payhandleClientService;

    @PostMapping(PayConfigUrl.Url_accountBalance)
    public Result accountBalance(){
        String mon= DateUtils.getStrDate(new Date(),"yyyy-MM");
        int logId=0;
        //2、从总库找出有效单位列表companyList
        List<EntityCompanyList> companyList=companyListInfoService.selectCompanyList();
        for (EntityCompanyList entityCompanyList : companyList) {
            try {
                //遍历companyList，找出未完成“上月结余”任务的单位：
                EntityTimingtaskLog entityTimingtaskLog=timingtaskLogService.selectTimingtaskLogs(entityCompanyList.getComId(),mon);
                //如果找不到记录：log_id := 0，执行3、4、5；
                if (entityTimingtaskLog==null){
                    //3、逐个单位从分库找出有效的账户信息accountList
                    List<EntityXfAccountInfo> entityXfAccountInfoList=xfAccountInfoService.selectAccountList(entityCompanyList.getComId());
                    //如果有记录：调用4（参数：com_id、month、accountList）
                    if (entityXfAccountInfoList.size()>0){
                        for (EntityXfAccountInfo entityXfAccountInfo : entityXfAccountInfoList) {
                            EntityXfRecord entityXfRecord=new EntityXfRecord();
                            entityXfRecord.setComId(entityCompanyList.getComId());
                            entityXfRecord.setOpType(100L);
                            entityXfRecord.setOpTypeDiff(0L);
                            entityXfRecord.setConsState(100);
                            entityXfRecord.setPayState(100);
                            entityXfRecord.setPId(entityXfAccountInfo.getPId());
                            entityXfRecord.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                            entityXfRecord.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                            entityXfRecord.setAccountNo(entityXfAccountInfo.getAccountNo());
                            Date date=new Date();
                            entityXfRecord.setConsTime(date);
                            entityXfRecord.setCreateTime(date);
                            entityXfRecord.setMonthValue(DateUtils.getStrDate(new Date(),"yyyyMM"));
                            xfRecordFeign.sveXfRecord(entityXfRecord);
                        }
                    }
                    //5、总库定时任务日志timingtask_log添加已完成记录
                    Boolean i=timingtaskLogService.saveTimingtaskLog(entityCompanyList.getComId(),logId,mon);
                /*if (!i){
                    return ResultUtil.error(ResultEnum.Err_2009);
                }
                return ResultUtil.success();*/
                }else {
                    //找到记录：如果status != 1，执行3、4、5；
                    if (entityTimingtaskLog.getStatus() !=1){
                        logId=entityTimingtaskLog.getId();
                        //3、逐个单位从分库找出有效的账户信息accountList
                        List<EntityXfAccountInfo> entityXfAccountInfoList=xfAccountInfoService.selectAccountList(entityCompanyList.getComId());
                        //如果有记录：调用4（参数：com_id、month、accountList）
                        if (entityXfAccountInfoList.size()>0){
                            for (EntityXfAccountInfo entityXfAccountInfo : entityXfAccountInfoList) {
                                EntityXfRecord entityXfRecord=new EntityXfRecord();
                                entityXfRecord.setComId(entityCompanyList.getComId());
                                entityXfRecord.setOpType(100L);
                                entityXfRecord.setOpTypeDiff(0L);
                                entityXfRecord.setConsState(100);
                                entityXfRecord.setPayState(100);
                                entityXfRecord.setPId(entityXfAccountInfo.getPId());
                                entityXfRecord.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                                entityXfRecord.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                                entityXfRecord.setAccountNo(entityXfAccountInfo.getAccountNo());
                                Date date=new Date();
                                entityXfRecord.setConsTime(date);
                                entityXfRecord.setCreateTime(date);
                                entityXfRecord.setMonthValue(DateUtils.getStrDate(new Date(),"yyyyMM"));
                                xfRecordFeign.sveXfRecord(entityXfRecord);
                            }
                        }
                        //5、总库定时任务日志timingtask_log添加已完成记录
                        Boolean i=timingtaskLogService.saveTimingtaskLog(entityCompanyList.getComId(),logId,mon);
                    /*if (!i){
                        return ResultUtil.error(ResultEnum.Err_2009);
                    }
                    return ResultUtil.success();*/
                    }
                }
            }catch (Exception e){

            }
        }
        return ResultUtil.success();
    }


    /**
     * 缴费定时任务
     */
    @GetMapping(PayConfigUrl.URL_timerJFXM)
    public void timerJFXM(){
        timerJFXMHandle(100l);
        timerJFXMHandle(600l);
    }

    /**
     * 缴费定时任务
     */
 //   @GetMapping(PayConfigUrl.URL_timerJFXM)
    public void timerJFXMHandle(Long comId){

        log.info("执行定时任务  NQSeFBT3  【{}】【{}】" ,comId,new Date());

        if(comId==null)  return;
        List<FeeItemXMVo> feeItemXMVoList = feeItemService.getItemListXM(comId);
        log.info("获取到列表 Ts9Xswpj   【{}】【{}】" ,comId,feeItemXMVoList);
        if(feeItemXMVoList==null || feeItemXMVoList.size()==0)  return;



        for (FeeItemXMVo feeItemXMVo: feeItemXMVoList){
            if(feeItemXMVo.getTagId()==null || feeItemXMVo.getTagId()==0){
                log.info("标签空");
                continue;
            }
            if(CommonUtil.isNull(feeItemXMVo.getDateList())){
                log.info("日期空");
                continue;
            }

            // 输出本周本月的日期
            String[] parts = feeItemXMVo.getDateList().split(",");
            List<String> dayList1 = Arrays.asList(parts);
            int days = dayList1.size() ;

            if(days == 0){
                log.info("天数空");
                continue;
            }

            int size = 300;

            Page<EntityPersonTagRelation> tagRelationPage =  personTagRelationService.getByComId(feeItemXMVo.getComId(),feeItemXMVo.getTagId(),1,size);
            if(tagRelationPage.getTotal()==0l){
                log.info("人员空");
                continue;
            }



            EntityXfRecordProcess entityXfRecordProcess =new EntityXfRecordProcess();
            if((feeItemXMVo.getTagId()==116 || feeItemXMVo.getTagId()==117) && feeItemXMVo.getComId()==217l){
                entityXfRecordProcess.setComId(feeItemXMVo.getComId());
                entityXfRecordProcess.setDeviceNo("00000000");
                entityXfRecordProcess.setDeviceName("缴费成功");
                entityXfRecordProcess.setPointId(0l);
                entityXfRecordProcess.setPointName("缴费成功");
                entityXfRecordProcess.setMerchId(feeItemXMVo.getAccountId().longValue());
                if(entityXfRecordProcess.getMerchId()!=0l){
                    //merchName
                    EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.GetMerchInfo(feeItemXMVo.getComId(),entityXfRecordProcess.getMerchId());
                    if(entityXfMerchantInfo!=null){
                        entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
                    }
                }
                entityXfRecordProcess.setMealDate(new Date());
                entityXfRecordProcess.setConsState(111);
                entityXfRecordProcess.setConsType(1);
                entityXfRecordProcess.setOpType(12l);
                entityXfRecordProcess.setOpTypeDiff(100l);
                entityXfRecordProcess.setPayWay(0);
                entityXfRecordProcess.setPayState(1);
                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(new Date(),"yyyyMM"));
                entityXfRecordProcess.setReserved1("贫困生免费");
            }



//            System.out.println(tagRelationPage.getPages());
            for (int i =1;i<=tagRelationPage.getPages();i++){
                Page<EntityPersonTagRelation> tagRelationPage2 =  personTagRelationService.getByComId(feeItemXMVo.getComId(),feeItemXMVo.getTagId(),i,size);
                for (EntityPersonTagRelation entityPersonTagRelation:tagRelationPage2.getRecords()){

                //    System.out.println(entityPersonTagRelation);

                    //关联请假判断
                    int perLeave = 0 ;
                    if(feeItemXMVo.getIfLeave()==1){
                        perLeave = xfMealLeaveService.perLeaveDays(feeItemXMVo.getComId(),entityPersonTagRelation.getPId(),2,dayList1);
                    }


                    Integer money = (days-perLeave)*feeItemXMVo.getDayAmount();

                    if(money == 0){
                        continue;
                    }

                    //贫困学生免费
                    if((feeItemXMVo.getTagId()==116 || feeItemXMVo.getTagId()==117) && feeItemXMVo.getComId()==217l){
                        try {
                            EntityXfRecordProcess entityXfRecordProcess2  = DeepCopyUtil.deepCopy(entityXfRecordProcess);

                            String dateStr = "2025";
                            String orderNo = "JF" + String.format("%08d", feeItemXMVo.getItemId()) + "P" + String.format("%08d", entityPersonTagRelation.getPId())+ "D" +dateStr;

                            entityXfRecordProcess2.setRealMoney(0l);
                            entityXfRecordProcess2.setConsMoney(-1l*money);
                            entityXfRecordProcess2.setDiscount(1l*money);
                            entityXfRecordProcess2.setPId(entityPersonTagRelation.getPId());
                            entityXfRecordProcess2.setDeptId(entityPersonTagRelation.getDeptId());
                            entityXfRecordProcess2.setOrderNo(orderNo);
                            entityXfRecordProcess2.setPlatOrderNo(orderNo);
                            entityXfRecordProcess2.setPayTime(new Date());
                            entityXfRecordProcess2.setCreateTime(entityXfRecordProcess2.getPayTime());
                            entityXfRecordProcess2.setConsTime(entityXfRecordProcess2.getPayTime());
                            entityXfRecordProcess2.setPName(entityPersonTagRelation.getPName());
                            entityXfRecordProcess2.setPCode(entityPersonTagRelation.getPCode());
                            entityXfRecordProcess2.setDeptName(entityPersonTagRelation.getDeptName());

                            FeeData feeData =new FeeData();
                            feeData.setComId(feeItemXMVo.getComId());
                            feeData.setItemId(feeItemXMVo.getItemId());
                            feeData.setPId(entityPersonTagRelation.getPId().intValue());
                            feeData.setDeptId(entityPersonTagRelation.getDeptId().intValue());
                            feeData.setPlanMoney(money);
                            feeData.setCompleteMoney(money);
                            feeData.setDataStatus(4);
                            feeData.setOrderNo(orderNo);
                            feeData.setTradeNo(orderNo);
                            feeData.setFeeTime(new Date());
                            feeDataService.addFeeDataFree(feeItemXMVo.getComId(), feeData, entityXfRecordProcess2);

                            payhandleClientService.SyncOrder(entityXfRecordProcess2);


                            String mo = AcpService.stringAmount(money.toString());

                            //发送公众号MQ消息 TODO
                            GzhMsgRequest gzhMsgRequest = new GzhMsgRequest();
                            gzhMsgRequest.setComId(feeData.getComId());
                            gzhMsgRequest.setPId(feeData.getPId().longValue());
                            gzhMsgRequest.setType(5);
                            gzhMsgRequest.getParams().setPayMoney( "0元，优惠"+mo +"元" );
                            gzhMsgRequest.getParams().setItemName(feeItemXMVo.getItemName());
                            gzhMsgRequest.getParams().setPayTime(DateUtil.formatDate(feeItemXMVo.getStopDate()));
                            gzhMsgRequest.getParams().setOrderNo(feeData.getOrderNo());
                            gzhMsgRequest.getParams().setUserName(entityPersonTagRelation.getPName());
                            this.mqSimpleFeign.gzhMsg(gzhMsgRequest);

                            log.info("发送公众号消息 v0ThYStR 【{}】【{}】 " ,gzhMsgRequest,feeData);

                        }catch (Exception e){
                            log.error("添加定时缴费异常 cadV9WvO  【{}】",e);
                        }
                        continue;
                    }


                    try {

                        FeeData feeData =new FeeData();
                        feeData.setComId(feeItemXMVo.getComId());
                        feeData.setItemId(feeItemXMVo.getItemId());
                        feeData.setPId(entityPersonTagRelation.getPId().intValue());
                        feeData.setDeptId(entityPersonTagRelation.getDeptId().intValue());
                        feeData.setPlanMoney(money);
                        feeDataService.addFeeDataOne(feeItemXMVo.getComId(),feeData);


                        String  mo = AcpService.stringAmount(money.toString());

                        //发送公众号MQ消息 TODO
                        GzhMsgRequest gzhMsgRequest = new GzhMsgRequest();
                        gzhMsgRequest.setComId(feeData.getComId());
                        gzhMsgRequest.setPId(feeData.getPId().longValue());
                        gzhMsgRequest.setType(5);
                        gzhMsgRequest.getParams().setPayMoney( mo +"元" );
                        gzhMsgRequest.getParams().setItemName(feeItemXMVo.getItemName());
                        gzhMsgRequest.getParams().setPayTime(DateUtil.formatDate(feeItemXMVo.getStopDate()));
                        gzhMsgRequest.getParams().setOrderNo(feeData.getOrderNo());
                        gzhMsgRequest.getParams().setUserName(entityPersonTagRelation.getPName());
                        this.mqSimpleFeign.gzhMsg(gzhMsgRequest);

                        log.info("发送公众号消息 v0ThYStR 【{}】【{}】 " ,gzhMsgRequest,feeData);

                    }catch (Exception e){
                        log.error("添加定时缴费异常 cadV9WvO  【{}】",e);
                    }



                    
                }
            }

//            feeItemService.startFeeItem(feeItemXMVo.getComId(), feeItemXMVo);
        }

    }


    /**
     * 缴费公众号通知定时任务
     */
    @GetMapping(PayConfigUrl.URL_timerJFGzhMsg)
    public void timerJFGzhMsg(Long comId) {

        int size = 50;

        Page<FeeDataGzhVo> feeDataGzhVoPage = feeDataService.getItemDateGzh(comId, 1, size);

        if (feeDataGzhVoPage.getTotal() == 0l) {
            log.info("77Snk9Ml 消息空");
            return;
        }


        for (int i = 1; i <= feeDataGzhVoPage.getPages(); i++) {
            Page<FeeDataGzhVo> feeDataGzhVoPage2 = feeDataService.getItemDateGzh(comId, i, size);
            for (FeeDataGzhVo feeDataGzhVo : feeDataGzhVoPage2.getRecords()) {

                Integer money = feeDataGzhVo.getPlanMoney();

                try {

                    String mo = AcpService.stringAmount(money.toString());

                    //发送公众号MQ消息 TODO
                    GzhMsgRequest gzhMsgRequest = new GzhMsgRequest();
                    gzhMsgRequest.setComId(feeDataGzhVo.getComId());
                    gzhMsgRequest.setPId(feeDataGzhVo.getPId());
                    gzhMsgRequest.setType(5);
                    gzhMsgRequest.getParams().setPayMoney(mo + "元");
                    gzhMsgRequest.getParams().setItemName(feeDataGzhVo.getItemName());
                    gzhMsgRequest.getParams().setPayTime(DateUtil.formatDate(feeDataGzhVo.getStopDate()));
                    gzhMsgRequest.getParams().setOrderNo(feeDataGzhVo.getOrderNo());
                    gzhMsgRequest.getParams().setUserName(feeDataGzhVo.getPName());
                    mqSimpleFeign.gzhMsg(gzhMsgRequest);

                    log.info("发送公众号消息 U9JKAcj5 【{}】【{}】 ", gzhMsgRequest, feeDataGzhVo);

                } catch (Exception e) {
                    log.error("添加定时缴费异常 k2N8LpV8  【{}】", e);
                }

            }
        }

    }



    //定时任务处理支付中的订单
    @GetMapping(PayConfigUrl.URL_paymentTimingGzh)
    public void paymentTimingGzh(@RequestParam("consState") Integer consState) {
        try {
            paymentTimings(1L, consState);
            log.info("定时任务处理支付中的订单:处理库一完成】");
            paymentTimings(600L, consState);
            log.info("定时任务处理支付中的订单:处理库二完成】");
        } catch (Exception e) {
            log.info("请求方式:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", e);
        }
    }

    private void paymentTimings(Long comId, Integer consState) throws Exception {
        //1、从待支付表中查询状态为支付中的消费记录（5分钟前、60分钟内）
        List<EntityXfRecordProcess> list = xfRecordProcessService.selectPayment(comId, consState);
        for (EntityXfRecordProcess entityXfRecordProcess : list) {
            ugcapiFeign.Check(entityXfRecordProcess.getComId(),entityXfRecordProcess.getOrderNo());
        }
    }




    //http://localhost:9301/test456?comId=100
    //http://localhost:9302/test456?comId=600

    @Autowired
    XfSignOrderService xfSignOrderService;

    @GetMapping("/test4567")
    public void encodePhone() {
        System.out.println(xfSignOrderService.encode(1l,"",""));
        System.out.println(xfSignOrderService.decode(1l,"",""));
    }


}
